import numpy as np
import cv2
from moviepy.editor import VideoFileClip,AudioFileClip

##本文件最后生成的视频是把给定原始视频生成轮廓线，并且背景反转

################以下内容为配置参数，可以调整
# 设置参数，会影响最后生成的文件名，下面的参数也可以调节
low_threshold = 90  # Canny算法低阈值
high_threshold = 150  # Canny算法高阈值

# 视频文件路径
video_path = "wuyage.mp4" 
#当为False的时候则new_audio_path必须含有音乐
keep_original_audio = True  # 是否保留原始背景音乐
new_audio_path = "bufenshou.mp3"  # 新背景音乐文件路径

invert_colors = True  # 是否进行颜色反转
###############调整参数完毕

# 输出视频文件路径
output_path = video_path[:-4]+'_'+str(low_threshold)+'_'+str(high_threshold)+'.mp4'  

# 读取视频
clip = VideoFileClip(video_path)
#获取视频长度
video_duration = clip.duration

# 定义轮廓线风格化函数
def stylize_frame(frame):
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    edges = cv2.Canny(gray, low_threshold, high_threshold)
    contours, _ = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    contour_frame = cv2.drawContours(np.zeros_like(frame), contours, -1, (255, 255, 255), thickness=cv2.FILLED)
    if invert_colors:
        contour_frame = 255 - contour_frame
    return contour_frame

# 应用风格化
processed_clip = clip.fl_image(stylize_frame)

# 背景音乐选择
if keep_original_audio:
    audio_clip = clip.audio
elif new_audio_path:
    new_clip = AudioFileClip(new_audio_path)
    audio_clip = new_clip.subclip(0, video_duration)


if audio_clip:
    processed_clip = processed_clip.set_audio(audio_clip)

# 保存处理后的视频
processed_clip.write_videofile(output_path, codec='libx264', audio_codec='aac')

# 释放资源
clip.close()
processed_clip.close()
